package common.library.annotations;

import android.content.Context;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class InjectViewImp {
    public static void inject(Context context) {
        try {
            Class<? extends Context> aClass = context.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            if (declaredFields != null) {
                Method findViewById = aClass.getDeclaredMethod("findViewById", Integer.TYPE);
                Object view;
                int id;
                InjectView annotation;
                for (int i = 0; i < declaredFields.length; i++) {
                    annotation = declaredFields[i].getAnnotation(InjectView.class);
                    if (annotation != null) {
                        id = annotation.value();
                        declaredFields[i].setAccessible(true);
                        view = findViewById.invoke(context, id);
                        declaredFields[i].set(context, view);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
